package com.wfh.picture.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.wfh.picture.exception.ErrorCode;
import com.wfh.picture.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author FengHuan Wang
 * @Date 2025/5/11 13:17
 * @Version 1.0
 */
@Service
public class BasePictureUploadTemplateImpl extends BasePictureUploadTemplate {
    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 文件大小
        long size = multipartFile.getSize();
        final long ONE_M = 2014 * 1024;
        ThrowUtils.throwIf(size > ONE_M, ErrorCode.PARAMS_ERROR, "图片大小不能超过2M");
        // 文件格式
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> ALLOW = Arrays.asList("jpeg", "jpg", "png");
        ThrowUtils.throwIf(!ALLOW.contains(suffix), ErrorCode.PARAMS_ERROR, "图片格式不支持");
    }
}
